package com.kpmg.datalake.schedule.utils.ftp;

import com.jcraft.jsch.SftpProgressMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DecimalFormat;

/**
 * ftp 监控
 *
 * @author Alex.zhao [alex.zhao@kpmg.com]
 * @since Created on azhao6 on 2018-08-13 15:52:15
 */
public class FileProgressMonitor implements SftpProgressMonitor {
    private static final Logger logger = LoggerFactory.getLogger(FileProgressMonitor.class);
    /**
     * 记录已传输的数据总大小
     */
    private long transfer;
    /**
     * 记录文件总大小
     */
    private long fileSize;
    /**
     * 打印日志时间间隔
     */
    private int minInterval = 100;
    /**
     * 开始时间
     */
    private long start;
    /**
     * 格式化
     */
    private DecimalFormat df = new DecimalFormat("#.##");
    /**
     * 来源文件
     */
    private String srcFile;
    private long preTime;

    /**
     * 传输开始
     *
     * @param op   操作
     * @param src  原始路径
     * @param dest 存放路径
     * @param max  文件大小
     */
    @Override
    public void init(int op, String src, String dest, long max) {
        this.fileSize = max;
        this.srcFile = src;
        if (logger.isDebugEnabled()) {
            logger.debug("{} Transferring begin.", src);
        }
        start = System.currentTimeMillis();
    }

    /**
     * 传输中
     */
    @Override
    public boolean count(long count) {
        if (logger.isDebugEnabled()) {
            if (fileSize != 0 && transfer == 0) {
                logger.debug("{} Transferring progress message: {}%", srcFile, df.format(0));
                preTime = System.currentTimeMillis();
            }
            transfer += count;
            if (fileSize != 0) {
                long interval = System.currentTimeMillis() - preTime;
                if (transfer == fileSize || interval > minInterval) {
                    preTime = System.currentTimeMillis();
                    double d = ((double) transfer * 100) / (double) fileSize;
                    logger.debug("{} Transferring progress message: {}%", srcFile, df.format(d));
                }
            } else {
                logger.debug("{} Transferring progress message: {} ", srcFile, transfer);
            }
        }
        return true;
    }

    /**
     * 传输结束
     */
    @Override
    public void end() {
        logger.info("{} Transferring end. used time: {}ms", srcFile, System.currentTimeMillis() - start);
    }

}
